package com.topisv.tms.rest;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.CusStockMerge;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.stock.ViewCusStock;
import com.topisv.tms.rest.vo.AddOrdenoResult;
import com.topisv.tms.rest.vo.SkuStockResult;
import com.topisv.tms.service.CusStockMergeService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.stock.ViewCusStockService;
import com.topisv.tms.utils.JsonUtil;

import net.sf.json.JSONObject;

/**
 * OMS操作接口
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/api/oms")
public class APICusStockController {
	private static final Logger log = LoggerFactory.getLogger(APICusStockController.class);
	
	@Autowired
	private ViewCusStockService viewCusStockService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private CusStockMergeService cusStockMergeService;
	@Autowired
	private EdiOrderService ediOrderService;
	
	////////////////////////////////////////////分页查询商品库存信息通过rest方式/////////////////////////////////////////////////////////
	
	/**
	 * 分页查看商品库存
	 * @param customerCode
	 * @param warehouseCode
	 * @param pageNumber
	 * @param pageSize
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "pageRestStock")
	public void pageRestStock(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "pageNumber") int pageNumber,
			@RequestParam(value = "pageSize") int pageSize,
			HttpServletRequest request, HttpServletResponse response){
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("网点编码==" + warehouseCode);
			log.info("第几页==" + pageNumber);
			log.info("每页显示数量==" + pageSize);
			if(pageSize>100){
				json.put("status", "0");
				json.put("content", "请求的每页数量请限制在100以内");
				out.print(json.toString());
				log.info("pageRestStock==" + json.toString());
				return;
			}
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("pageRestStock==" + json.toString());
				return;
			}
			Map<String, Object> filterParams =new HashMap<String, Object>();
			filterParams.put("EQ_customer.customerCode", customerCode);
			filterParams.put("EQ_warehouseCode", warehouseCode);
			Page<ViewCusStock> viewCusStocks=this.viewCusStockService.loadViewStock(filterParams, pageNumber, pageSize);
			
			//是否限制订单流入的商家
			if("1".equals(customers.getSubStock())){
				List<ViewCusStock> vs=viewCusStocks.getContent();
				for(ViewCusStock v:vs){
					CusStockMerge cusStockMerge=cusStockMergeService.findCustomerWarSku(customerCode, warehouseCode, v.getSku());
					if(cusStockMerge!=null){
						v.setOrderNum(v.getOrderNum()-cusStockMerge.getOrderNum());
					}
				}	
			}
			json.put("status", "1");
			json.put("content", viewCusStocks);
			out.print(json.toString());
			log.info("pageRestStock==" + json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("pageRestStock==" + json.toString());
			log.info("pageRestStockException==" + e);
			out.print(json.toString());
		}
	}
	
   ////////////////////////////////////////////分页查询商品库存信息通过AJAX跨域方式/////////////////////////////////////////////////////////
	/**
	 * 商品库存分页请求(跨域ajax方法)
	 * @param customerCode
	 * @param warehouseCode
	 * @param pageNumber
	 * @param pageSize
	 * @param callback
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "pageStock")
	public void pageStock(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "pageNumber") int pageNumber,
			@RequestParam(value = "pageSize") int pageSize,
			@RequestParam(value="jsonpcallback") String callback, 
			HttpServletRequest request, HttpServletResponse response){
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("网点编码==" + warehouseCode);
			log.info("第几页==" + pageNumber);
			log.info("每页显示数量==" + pageSize);
			if(pageSize>100){
				json.put("status", "0");
				json.put("content", "请求的每页数量请限制在100以内");
				out.print(json.toString());
				log.info("pageStock==" + json.toString());
				return;
			}
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("pageStock==" + json.toString());
				return;
			}
			Map<String, Object> filterParams =new HashMap<String, Object>();
			filterParams.put("EQ_customer.customerCode", customerCode);
			filterParams.put("EQ_warehouseCode", warehouseCode);
			Page<ViewCusStock> viewCusStocks=this.viewCusStockService.loadViewStock(filterParams, pageNumber, pageSize);
			
			//是否限制订单流入的商家
			if("1".equals(customers.getSubStock())){
				List<ViewCusStock> vs=viewCusStocks.getContent();
				for(ViewCusStock v:vs){
					CusStockMerge cusStockMerge=cusStockMergeService.findCustomerWarSku(customerCode, warehouseCode, v.getSku());
					if(cusStockMerge!=null){
						v.setOrderNum(v.getOrderNum()-cusStockMerge.getOrderNum());
					}
				}	
			}
			json.put("status", "1");
			json.put("content", viewCusStocks);
			out.print(callback+"("+json.toString()+")");
			log.info("pageStock==" + json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("pageStock==" + json.toString());
			log.info("pageStockException==" + e);
			out.print(json.toString());
		}
	}
	
    ////////////////////////////////////////////根据货号分页查询库存信息，返回的是库存的视图表结构/////////////////////////////////////////////////////////
	/**
	 * 根据货号查看单个商品库存
	 * @param customerCode 商家编码
	 * @param bar 商品SKU编码
	 * @param warehouseCode 网点编码
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "pageBarStock", method = RequestMethod.POST)
	public void pageBarStock(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "bar") String bar,
			@RequestParam(value = "pageNumber") int pageNumber,
			@RequestParam(value = "pageSize") int pageSize,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("商品货号==" + bar);
			log.info("网点编码==" + warehouseCode);
			log.info("第几页==" + pageNumber);
			log.info("每页显示数量==" + pageSize);
			if(pageSize>100){
				json.put("status", "0");
				json.put("content", "请求的每页数量请限制在100以内");
				out.print(json.toString());
				log.info("pageBarStock==" + json.toString());
				return;
			}
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("pageBarStock==" + json.toString());
				return;
			}
			
			Map<String, Object> filterParams =new HashMap<String, Object>();
			filterParams.put("EQ_customer.customerCode", customerCode);
			filterParams.put("EQ_warehouseCode", warehouseCode);
			filterParams.put("EQ_bar", bar);
			Page<ViewCusStock> viewCusStocks=this.viewCusStockService.loadViewStock(filterParams, pageNumber, pageSize);
			
			List<ViewCusStock> lists=viewCusStocks.getContent();
			//是否限制订单流入的商家
			if("1".equals(customers.getSubStock())){
				for(ViewCusStock v:lists){
					CusStockMerge cusStockMerge=cusStockMergeService.findCustomerWarSku(customerCode, warehouseCode, v.getSku());
					if(cusStockMerge!=null){
						v.setOrderNum(v.getOrderNum()-cusStockMerge.getOrderNum());
					}
				}
			}
		
			json.put("status", "1");
			json.put("content", viewCusStocks);
			log.info("pageBarStock==" + json.toString());
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("pageBarStock==" + json.toString());
			log.info("pageBarStockException==" + e);
			out.print(json.toString());
		}
	}
	
	 ////////////////////////////////////////////根据多个SKU编码查询商品的库存信息，此接口存在的目的是对应OMS的拆分订单模块，返回的是SkuStockResult的一个list/////////////////////////////////////////////////////////
	
	/**
	 * 根据SKU查看多个商品的库存:分割
	 * @param customerCode
	 * @param skus
	 * @param warehouseCode
	 * @param request
	 * @param response
	 * return status error,success
	 */
	@RequestMapping(value = "getSkusStock", method = RequestMethod.POST)
	public void getSkusStock(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "sku") String skus,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("商品编码列表==" + skus);
			log.info("网点编码==" + warehouseCode);
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("getSkuStock==" + json.toString());
				return;
			}
			if(skus==null){
				json.put("status", "0");
				json.put("content", "skus参数不正确");
				out.print(json.toString());
				log.info("getSkuStock==" + json.toString());
				return;
			}
			String[] lists=skus.split(":");
			if(lists.length>100){
				json.put("status", "0");
				json.put("content", "请限制查询的商品数量");
				out.print(json.toString());
				log.info("getSkusStock==" + json.toString());
				return;
			}
            List<SkuStockResult> rs=new ArrayList<SkuStockResult>();
			for(String sku:lists){
				SkuStockResult r=new SkuStockResult();
				r.setSku(sku);
				ViewCusStock v=null;
				try {
					 v=this.viewCusStockService.loadByCondition(customerCode, warehouseCode, sku);
				} catch (Exception e) {
					 r.setStatus("error");
				}
				if(v==null){
					r.setStatus("error");
				}else{
					r.setStatus("success");
					CusStockMerge cusStockMerge=cusStockMergeService.findCustomerWarSku(customerCode, warehouseCode, sku);
					if(cusStockMerge!=null){
						v.setOrderNum(v.getOrderNum()-cusStockMerge.getOrderNum());
					}
				}
				r.setViewCusStock(v);
				rs.add(r);
			}
			
			json.put("status", "1");
			json.put("content", rs);
			log.info("getSkusStock==" + json.toString());
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("getSkusStock==" + json.toString());
			log.info("getSkusStockException==" + e);
			out.print(json.toString());
		}
	}
	
	 ////////////////////////////////////////////根据单个SKU编码查询商品的库存信息，返回的是SkuStockResult的一个list/////////////////////////////////////////////////////////

	/**
	 * 根据SKU查看单个商品库存
	 * @param customerCode 商家编码
	 * @param sku 商品SKU编码
	 * @param warehouseCode 网点编码
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "getSkuStock", method = RequestMethod.POST)
	public void getSkuStock(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("商品编码==" + sku);
			log.info("网点编码==" + warehouseCode);
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("getSkuStock==" + json.toString());
				return;
			}
			ViewCusStock v=this.viewCusStockService.loadByCondition(customerCode, warehouseCode, sku);
			SkuStockResult r=new SkuStockResult();
			r.setViewCusStock(v);
			r.setSku(sku);
			if(v==null){
				r.setStatus("error");
			}else{
				r.setStatus("success");
				//是否限制订单流入的商家
				if("1".equals(customers.getSubStock())){
					CusStockMerge cusStockMerge=cusStockMergeService.findCustomerWarSku(customerCode, warehouseCode, sku);
					if(cusStockMerge!=null){
						v.setOrderNum(v.getOrderNum()-cusStockMerge.getOrderNum());
					}
				}
			}
			
			json.put("status", "1");
			json.put("content", r);
			log.info("getSkuStock==" + json.toString());
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("getSkuStock==" + json.toString());
			log.info("getSkuStockException==" + e);
			out.print(json.toString());
		}
	}
	
	 ////////////////////////////////////////////保存单个订单的数据/////////////////////////////////////////////////////////

	/**
	 * 保存订单数据(单条)
	 * @param ordenoJson
	 * @param customerCode
	 * @param warehouseCode
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "addOrdeno", method = RequestMethod.POST)
	public void addOrdeno(@RequestParam(value = "ordenoJson") String ordenoJson,
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		AddOrdenoResult result=new AddOrdenoResult();
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("订单数据==" + ordenoJson);
			log.info("网点编码==" + warehouseCode);
			if(ordenoJson==null){
				json.put("status", "0");
				json.put("content", "参数不正确");
				out.print(json.toString());
				log.info("addOrdeno==" + json.toString());
				return;
			}
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("addOrdeno==" + json.toString());
				return;
			}
			
			EdiOrder e=JsonUtil.getEdiOrder(ordenoJson);
			e.setCustomerCode(customerCode);
			e=ediOrderService.saveEdiOrderOMS(e, customerCode, warehouseCode);
			if("cancel".equals(e.getStatus())){
				/*result.setOrdeno(e.getOrdeno());
				result.setResult(e.getMessage());
				result.setStatus("error");*/
				json.put("status", "0");
				json.put("content", e.getMessage());
				out.print(json.toString());
				log.info("addOrdeno==" + json.toString());
				return;
			}else{
				result.setOrdeno(e.getOrdeno());
				result.setResult("接收成功");
				result.setStatus("success");
			}
			json.put("status", "1");
			json.put("content", result);
			out.print(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("addOrdenoException==" + e);
			out.print(json.toString());
		}
		log.info("addOrdeno==" + json.toString());
	}
	
	
     ////////////////////////////////////////////保存多个订单的数据/////////////////////////////////////////////////////////

	/**
	 * 保存订单数据(多条)
	 * @param ordenoJson
	 * @param customerCode
	 * @param warehouseCode
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "addOrdenos", method = RequestMethod.POST)
	public void addOrdenos(@RequestParam(value = "ordenoJson") String ordenoJson,
			@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			log.info("商家编码==" + customerCode);
			log.info("订单数据==" + ordenoJson);
			log.info("网点编码==" + warehouseCode);
			if(ordenoJson==null){
				json.put("status", "0");
				json.put("content", "参数不正确");
				out.print(json.toString());
				log.info("addOrdenos==" + json.toString());
				return;
			}
			Customers customers=this.customersService.findByCustomerCode(customerCode);
			if(customers==null){
				json.put("status", "0");
				json.put("content", "商家编码不存在");
				out.print(json.toString());
				log.info("addOrdenos==" + json.toString());
				return;
			}
			
			List<EdiOrder> es=JsonUtil.getEdiOrders(ordenoJson);
			List<AddOrdenoResult> results=new ArrayList<AddOrdenoResult>();
			for(int i=0;i<es.size();i++){
				EdiOrder e=es.get(i);
				AddOrdenoResult result=new AddOrdenoResult();
				result.setOrdeno(e.getOrdeno());
				try {
					e.setCustomerCode(customerCode);
					ediOrderService.saveEdiOrderOMS(e, customerCode, warehouseCode);
					result.setResult("接收成功");
					result.setStatus("success");
					if("cancel".equals(e.getStatus())){
						result.setResult(e.getMessage());
						result.setStatus("error");
					}
				} catch (Exception e2) {
					result.setResult(e2.getMessage());
					result.setStatus("error");
				}
				results.add(result);
			}
			json.put("status", "1");
			json.put("content", results);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			log.info("addOrdenosException==" + e.getStackTrace());
			out.print(json.toString());
		}
		log.info("addOrdenos==" + json.toString());
	}

}
